package com.song.dubbo3service.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;

import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;

/**
 * @Author SHI YUAN
 * @DATE 2022/2/8 1:49 PM
 * @Version 1.0
 * @Desc
 */
@Slf4j
@Activate(group = {PROVIDER})
public class DubboServiceResponseFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String tradeId = RpcContext.getServerAttachment().getAttachment("traceId");
        ThreadLocalUtil.putValue(tradeId);
        TraceUtils.setTraceId(tradeId);
        // 业务代码
        Result result = invoker.invoke(invocation);
        log.info("[DubboServiceResponseFilter] tradeId:{}, threadId:{}, result:{}",
                tradeId, Thread.currentThread().getId(), JSON.toJSONString(result));
        return result;
    }
}
